package dd.server;

import java.util.Set;

import org.w3c.dom.NamedNodeMap;

import server.ClientState;
import server.IProtocolHandler;
import server.Server;
import xml.Message;
import dd.model.Event;
import dd.model.serverModel;

/**
 * Server received the reportRequest and get the eventId which wants to generate the report
 */
public class GenerateReportResponseController implements IProtocolHandler {

	@Override
	public Message process(ClientState state, Message request) {
		NamedNodeMap map = request.contents.getFirstChild().getAttributes();
		// get information
		String eventId = map.getNamedItem("key").getNodeValue();
		System.out.println("GenerateReportResponseController received the ReportRequest, eventId : " + eventId);

		Event currentEvent = serverModel.getInstance().getEventByEventId(eventId);
		Set<String> clients = serverModel.getInstance().getClientIdsByEventId(eventId);

		String xmlString = Message.responseHeader(request.id()) + "<reportResponse>" + "<entry id='" + eventId
				+ "' type='" + currentEvent.getMode() + "' behavior='" + currentEvent.getType() + "' question='"
				+ currentEvent.getEventName() + "' numChoices='" + currentEvent.getNumberLines() + "' numRounds='"
				+ currentEvent.getNumberEdges() + "' created='' completed='" + currentEvent.getIscompleted() + "'/>"
				+ "</reportResponse></response>";
		Message message = new Message(xmlString);

		// send this response to all the client
		for (String client : clients) {
			if (Server.ids().contains(client)) { // if the client is still alive
				Server.getState(client).sendMessage(message);
			}
		}

		xmlString = Message.responseHeader(request.id())
				+ "<adminResponse key='Clients should receive report now!'></adminResponse></response>";
		message = new Message(xmlString);

		return message;
	}
}
